﻿namespace KeRui.Upload
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Reflection;

    internal class Log
    {
        private static ArrayList sErrorList = new ArrayList();
        private static EventLog sEventLog = null;

        public static void Error(string inMsg)
        {
            WriteEntry(inMsg, EventLogEntryType.Error);
        }

        public static void ExceptionDetails(Exception e)
        {
            try
            {
                WriteEntry(string.Format("{0} threw exception '{1}'.\r\n\r\n{2}", e.Source, e.Message, e.StackTrace), EventLogEntryType.Error);
            }
            catch
            {
            }
        }

        private static EventLog GetEventLog()
        {
            if (sEventLog == null)
            {
                string name = Assembly.GetExecutingAssembly().GetName().Name;
                if (!EventLog.SourceExists(name))
                {
                    EventLog.CreateEventSource(name, "Application");
                }
                sEventLog = new EventLog("Application", ".", name);
            }
            return sEventLog;
        }

        public static void Success(string inMsg)
        {
            WriteEntry(inMsg, EventLogEntryType.SuccessAudit);
        }

        public static void UniqueError(string inMsg)
        {
            UniqueError(inMsg, "");
        }

        public static void UniqueError(string inUniqueMsg, string inDescription)
        {
            if ((sErrorList.Count <= 15) && !sErrorList.Contains(inUniqueMsg))
            {
                sErrorList.Add(inUniqueMsg);
                Error(inUniqueMsg + inDescription);
                if (sErrorList.Count > 15)
                {
                    Error("Many errors have been raised. To avoid cluttering the Event Log no more will be recorded.");
                }
            }
        }

        private static void WriteEntry(string inMsg, EventLogEntryType inType)
        {
            try
            {
                GetEventLog().WriteEntry(inMsg, inType);
            }
            catch
            {
            }
        }
    }
}

